const app = getApp()
const util = require('../../../../../utils/util.js');
const api = require('../../../../../config/api.js');
const recorderManager = wx.getRecorderManager();
var recordInterval = null;
var timeCountDown = null;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    ordTheme: {},// 主题基本信息
    ordThemeAuxiliary: { 
      "preview": 0,
      "showDiaochaSubmit": false,
      "showCepingSubmit": false,
      "showTimeCountDown": false, //倒计时显示
      "examTime": 0,//倒计时时间
      "examPanel": 0,//测评答案显示控制  0 全部题目 1 错题解析
      'themeNoticeShow': false,//是否弹出主题公告
    },
    // 数据信息
    dataInfoList: [],
    // 推荐信息
    ordThemeRecommendList: [],
    // 奖品信息
    reward: {},
    // 主题设置信息
    ordThemeSetting: {},
    // 其他信息
    otherInfo: { 
      "themeUserNickname": "", 
      "themeUserImage": "", 
      "verifyCode": '',//验证码
      "ratifyShow": false, //是否显示问卷设置的弹出层
    },
    // 回答的信息
    themeAnswerSubmit: {
      "openid": "",
      "themeid": "",
      "themeAnswerSubmitList": []
    },
    // 提交后的返回信息
    themeAnswerSubmitResult: {},
  },
  onLoad: function (options) {
    var _this = this;
    var themeid = options.themeid;
    var preview = options.preview;
    var openid = app.globalData.logininfo.openid;
    _this.setData({
      ["themeAnswerSubmit.openid"]: openid,
      ["themeAnswerSubmit.themeid"]: themeid,
      ["ordThemeAuxiliary.preview"]: preview,
    })
    // 获取主题信息
    _this.getThemeInfoBySelect();
  },
  /**
   * 获取主题信息
   */
  getThemeInfoBySelect: function () {
    var _this = this;
    var themeid = _this.data.themeAnswerSubmit.themeid;
    var openid = app.globalData.logininfo.openid;
    if (openid != null && openid != "") {
      // 已登录
      util.post(api.fetchToken()).then(function (res) {
        if (res.access_token != '') {
          return Promise.resolve({
            access_token: res.access_token
          });
        }
      }).then(function (res) {
        var data = {};
        data.openid = openid;
        data.themeid = themeid;
        data.access_token = res.access_token;
        util.post(api.Interest_GetThemeInfoBySelectApi, data).then(res => {
          if (res.code == 200) {
            var dataInfoList =res.result.dataInfoList;
            for (var i = 0; i < dataInfoList.length; i++) {
              var dataInfo = dataInfoList[i];
              switch (dataInfo.type) {
                case 3:
                  dataInfo.startDate = "00:00";
                  dataInfo.voiceBoFangImage = api.AudioNoBoFangImage_Name;
                  dataInfo.currentTime = 0;
                  break;
                case 4:
                  var videoid = "myVideo" + new Date().getTime() + i;
                  dataInfo.videoid = videoid;
                  break;
              }
              dataInfoList[i] = dataInfo;
            }
            var ordTheme = res.result.ordTheme;
            var ordThemeSetting = res.result.ordThemeSetting;
            var preview = _this.data.ordThemeAuxiliary.preview;
            if (null != ordThemeSetting && ordThemeSetting.useTime != null && parseInt(ordThemeSetting.useTime) > 0){
              _this.setData({
                ["ordThemeAuxiliary.examTime"]: parseInt(ordThemeSetting.useTime)
              })
            }
            _this.setData({
              ordTheme: res.result.ordTheme,
              dataInfoList: dataInfoList,
              reward: res.result.reward,
              ordThemeSetting: ordThemeSetting,
              ordThemeRecommendList: res.result.ordThemeRecommendList,
              ["otherInfo.themeUserImage"]: res.result.themeUserImage,
              ["otherInfo.themeUserNickname"]: res.result.themeUserNickname,
            })
            if (preview != 1) {
              _this.ratifyShow();
            }
          }
        })
      })
    }
  },

  ratifyShow: function(){
    var _this = this;
    var ordTheme = _this.data.ordTheme;
    var ordThemeSetting = _this.data.ordThemeSetting;
    var preview = _this.data.ordThemeAuxiliary.preview;
    if (null != ordThemeSetting && preview != 1) {
      if (ordThemeSetting.isOpenReward == 1 || (ordThemeSetting.verificationCode != null && String(ordThemeSetting.verificationCode).length > 0) || (ordThemeSetting.useTime != null && String(ordThemeSetting.useTime).length > 0)) {
        _this.setData({
          ["otherInfo.ratifyShow"]: true
        })
      }else if (ordTheme.themeNotice != null && String(ordTheme.themeNotice).length > 0) {
        _this.setData({
          ["ordThemeAuxiliary.themeNoticeShow"]: true
        })
      }
    }
  },

  /**
   * 单选
   */
  selectRadioOption: function(e){
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var optionindex = e.currentTarget.dataset.optionindex;
    var dataInfo = _this.data.dataInfoList[index];
    var optionFormList = dataInfo.optionFormList;
    for (var i = 0; i < optionFormList.length;i++){
      if (i == optionindex){
        _this.setData({
          ["dataInfoList[" + index +"].optionFormList["+i+"].click"]: 1
        })
      }else{
        _this.setData({
          ["dataInfoList[" + index + "].optionFormList[" + i + "].click"]: 0
        })
      }
    }
  },

  /**
   * 多选
   */
  multiSelect: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var optionindex = e.currentTarget.dataset.optionindex;
    var click = _this.data.dataInfoList[index].optionFormList[optionindex].click;
    _this.setData({
      ["dataInfoList[" + index + "].optionFormList[" + optionindex + "].click"]: click == 1 ? 0 : 1
    })
  },

  /**
   * 星级
   */
  selectLeve: function(e){
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var optionindex = e.currentTarget.dataset.optionindex;
    var level = e.currentTarget.dataset.level;
    _this.setData({
      ["dataInfoList[" + index + "].optionFormList[" + optionindex + "].level"]: parseInt(level + 1)
    })
  },

  /**
   * 判断
   */
  selectPdOption: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index;
    var optionindex = e.currentTarget.dataset.optionindex;
    var answer = e.currentTarget.dataset.answer;
    _this.setData({
      ["dataInfoList[" + index + "].optionFormList[" + optionindex + "].click"]: answer
    })
  },

  /**
   * 问答输入框：鼠标移入事件
   */
  openUserAnswerTextarea: function (e) {
    var _this = this;;
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].showAnswerTextarea"]: true,
    })
  },

   /**
   * 问答输入框：鼠标移出事件
   */
  closeUserAnswerTextarea: function (e) {
    var _this = this;
    var index = e.currentTarget.dataset.index
    _this.setData({
      ["dataInfoList[" + index + "].showAnswerTextarea"]: false,
    })
  },

  /**
  * 问答输入事件
  */
  inputUserAnswerTextarea: function (e) {
    var _this = this;
    var value = e.detail.value.replace(/\s+/g, '');
    var index = e.currentTarget.dataset.index;
    _this.setData({
      ["dataInfoList[" + index + "].answer"]: value
    })
  },

  /**
   * 提交问卷
   */
  saveDioacha: function(){
    var _this = this;
    _this.saveDioachaQuery(true);
  },

  /**
   * 提交
   */
  saveDioachaQuery: function(isCheck = true){
    var _this = this;
    if (isCheck) {
      if (!_this.checkData()) {
        return false;
      }
    }
    _this.optimizeData();
    // 已登录
    util.post(api.fetchToken()).then(function (res) {
      if (res.access_token != '') {
        return Promise.resolve({
          access_token: res.access_token
        });
      }
    }).then(function (res) {
      var contentType = _this.data.ordTheme.contentType;
      var data = _this.data.themeAnswerSubmit;
      data.access_token = res.access_token;
      if (contentType == 3){
        // 测评
        var useTime = _this.data.ordThemeSetting.useTime;
        if (useTime != null && String(useTime).length > 0) {
          data.useTime = useTime - _this.data.ordThemeAuxiliary.examTime;
        }
      }
      util.post(api.Interest_AnswerSumbitApi, data).then(res => {
        if (res.code == 200) {
          _this.setData({
            ["ordThemeAuxiliary.showDiaochaSubmit"]: true,
            ["ordThemeAuxiliary.showCepingSubmit"]: true,
            themeAnswerSubmitResult: res.result
          })
          wx.pageScrollTo({
            scrollTop: 0,
            duration: 300
          })
          if (null != timeCountDown) {
            _this.setData({
              ["ordThemeAuxiliary.showTimeCountDown"]: false
            })
            clearInterval(timeCountDown);
            timeCountDown = null;
          }
        }else{
          util.showToast(res.message, "none");
        }
      })
    })
  },

  /**
   * 校验数据
   */
  checkData: function(){
    var _this = this;
    var dataInfoList = _this.data.dataInfoList;
    for (var i = 0; i < dataInfoList.length; i++) {
      var dataInfo = dataInfoList[i];
      var optionFormList = dataInfo.optionFormList;
      // 7单选 8多选 9判断 10问答 11评星 12填空
      if (dataInfo.type == 7) {
        var answer = null
        for (var j = 0; j < optionFormList.length; j++) {
          if (optionFormList[j].click != null) {
            answer = optionFormList[j].click;
          }
        }
        if (answer == null) {
          util.showToast("单选题尚未完成", "none");
          return false;
        }
      }
      if (dataInfo.type == 8) {
        var answer = null
        for (var j = 0; j < optionFormList.length; j++) {
          if (optionFormList[j].click != null) {
            answer = optionFormList[j].click;
          }
        }
        if (answer == null) {
          util.showToast("多选题尚未完成", "none");
          return false;
        }
      }
      if (dataInfo.type == 9) {
        for (var j = 0; j < optionFormList.length; j++) {
          if (optionFormList[j].click == null) {
            util.showToast("判断题尚未完成", "none");
            return false;
          }
        }
      }
      if (dataInfo.type == 11) {
        for (var j = 0; j < optionFormList.length; j++) {
          if (optionFormList[j].level == null) {
            util.showToast("评星题尚未完成", "none");
            return false;
          }
        }
      }
      if (dataInfo.type == 12) {
        var answer = null
        for (var j = 0; j < optionFormList.length; j++) {
          if (optionFormList[j].click != null) {
            answer = optionFormList[j].click;
          }
        }
        if (answer == null) {
          util.showToast("填空题尚未完成", "none");
          return false;
        }
      }
    }
    return true;
  },

  /**
   * 优化数据
   */
  optimizeData: function(){
    var _this = this;
    var dataInfoList = _this.data.dataInfoList;
    var themeAnswerSubmitList = _this.data.themeAnswerSubmit.themeAnswerSubmitList;
    for (var i = 0; i < dataInfoList.length; i++) {
      var dataInfo = dataInfoList[i];
      var optionFormList = dataInfo.optionFormList;
      var themeProblemAnswerList = [];
      var themeAnswerSubmit = {};
      // 7单选 8多选 9判断 10问答 11评星 12填空
      if (dataInfo.type == 7 || dataInfo.type == 8 || dataInfo.type == 9 || dataInfo.type == 11 || dataInfo.type == 12){
        for (var j = 0; j < optionFormList.length; j++) {
          var themeProblemAnswer = {};
          themeProblemAnswer.index = j;
          if (dataInfo.type == 11) {
            themeProblemAnswer.isanswer = optionFormList[j].level;
          } else if (dataInfo.type == 9){
            // 判断题
            if (optionFormList[j].click == null || String(optionFormList[j].click).length <= 0){
              themeProblemAnswer.isanswer = "";
            }else{
              themeProblemAnswer.isanswer = optionFormList[j].click == 1 ? 1 : 0;
            }
          } else {
            themeProblemAnswer.isanswer = optionFormList[j].click == 1 ? 1 : 0;
          }
          themeProblemAnswerList.push(themeProblemAnswer);
        }
      } else if (dataInfo.type == 10) {
        //问答
        themeAnswerSubmit.answer = dataInfo.answer;
      }
      // 校验回答的信息里是否有此题目
      var isHasProblemid = false;
      var themeAnswerSubmitIndex = 0;
      for (var i = 0; i < themeAnswerSubmitList.length; i++) {
        if (themeAnswerSubmitList[i].problemid == dataInfo.id) {
          isHasProblemid = true;
          themeAnswerSubmitIndex = i;
        }
      }
      themeAnswerSubmit.problemid = dataInfo.id;
      themeAnswerSubmit.themeProblemAnswerList = themeProblemAnswerList;
      if (!isHasProblemid) {
        themeAnswerSubmitIndex = themeAnswerSubmitList.length;
      }
      _this.setData({
        ["themeAnswerSubmit.themeAnswerSubmitList[" + themeAnswerSubmitIndex + "]"]: themeAnswerSubmit
      })
    }
  },

  /**
   * 返回继续编辑
   */
  goback: function(){
    var _this = this
    wx.navigateBack({
      delta: 1
    })
  },

  /**
   * 跳转到公众号展示页面
   */
  navigateToWebView: function (e) {
    var ip = e.currentTarget.dataset.ip;
    var text = e.currentTarget.dataset.text;
    var type = e.currentTarget.dataset.type;
    if (type == 1) {
      wx.navigateTo({
        url: '/pages/home/webView/webView?src=' + text,
      })
    } else {
      wx.downloadFile({
        url: ip + text,
        success: function (res) {
          var filePath = res.tempFilePath;
          wx.openDocument({
            filePath: filePath,
            success: function (res) { }
          })
        }
      })
    }
  },

  /**
   * 使用微信内置地图查看位置
   */
  wxGetLocation: function (e) {
    var latitude = e.currentTarget.dataset.latitude;
    var longitude = e.currentTarget.dataset.longitude;
    wx.openLocation({
      latitude: latitude,//要去的纬度-地址
      longitude: longitude,//要去的经度-地址
    })
  },

  /**
   * 关闭面板
   */
  closeMC: function(){
    var _this = this
    _this.setData({
      ["ordThemeAuxiliary.showDiaochaSubmit"]: false,
      ["ordThemeAuxiliary.showCepingSubmit"]: false,
    })
  },

  /**
   * 播放或暂停动作
   */
  voiceBoFang: function (e) {
    var _this = this;
    var path = e.currentTarget.dataset.path;
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    var currentTime = e.currentTarget.dataset.currenttime;
    var voiceBoFangImage = e.currentTarget.dataset.voiceimage;
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (voiceBoFangImage == api.AudioBoFangImage_Name) {
      // 切换至暂停状态
      backgroundAudioManager.pause();//暂停播放音乐
      _this.setData({
        ["dataInfoList[" + index + "].voiceBoFangImage"]: api.AudioNoBoFangImage_Name
      });
    } else {
      // 切换至播放状态
      wx.stopBackgroundAudio();//暂停正在播放音乐
      backgroundAudioManager.startTime = currentTime;//设置音乐开始时间
      backgroundAudioManager.title = title;
      backgroundAudioManager.src = path;
      backgroundAudioManager.play();
      //    背景音频自然播放结束事件
      backgroundAudioManager.onEnded(function () {
        _this.setData({
          ["dataInfoList[" + index + "].currentTime"]: 0,
          ["dataInfoList[" + index + "].voiceBoFangImage"]: api.AudioNoBoFangImage_Name,
          ["dataInfoList[" + index + "].startDate"]: "00:00"
        });
      })
      //背景音频播放进度更新事件
      backgroundAudioManager.onTimeUpdate(function (callback) {
        var position = Math.round(backgroundAudioManager.currentTime);
        var voiceStartDate = util.digitalFormatTime(position);
        _this.setData({
          ["dataInfoList[" + index + "].currentTime"]: backgroundAudioManager.currentTime,
          ["dataInfoList[" + index + "].startDate"]: voiceStartDate
        });
      })

      _this.setData({
        ["dataInfoList[" + index + "].voiceBoFangImage"]: api.AudioBoFangImage_Name
      });
    }
  },

  /**
   * 播放音乐（滚动条事件）
   */
  voiceSlider: function (e) {
    var _this = this;
    var position = e.detail.value;
    var path = e.currentTarget.dataset.path;
    var index = e.currentTarget.dataset.index;
    var title = e.currentTarget.dataset.title;
    var currentTime = e.currentTarget.dataset.currenttime;
    var voiceBoFangImage = e.currentTarget.dataset.voiceimage;
    var voiceStartDate = util.digitalFormatTime(position);
    var backgroundAudioManager = wx.getBackgroundAudioManager();//获取全局唯一的背景音频管理器
    if (voiceBoFangImage == api.AudioBoFangImage_Name) {
      //正在播放状态：不知道为什么，录音的在调用backgroundAudioManager.seek(Math.floor(position))方法无效，所以改成一下这种方式
      e.currentTarget.dataset.currenttime = position;
      e.currentTarget.dataset.voiceimage = api.AudioNoBoFangImage_Name;
      _this.voiceBoFang(e);
    } else {
      // 未播放状态
      _this.setData({
        ["dataInfoList[" + index + "].currentTime"]: position,
        ["dataInfoList[" + index + "].startDate"]: voiceStartDate
      });
    }
  },

  /**
   * 测评类验证码输入
   */
  inputVerifyCode: function(e){
    var _this = this
    var value = e.detail.value.replace(/\s+/g, '')
    _this.setData({
      ["otherInfo.verifyCode"]: value,
    })
  },
  /**
  * 测评类验证码检查
  */
  checkVerifyCode: function () {
    var _this = this
    var verifyCode = _this.data.otherInfo.verifyCode;
    var verificationCode = _this.data.ordThemeSetting.verificationCode;
    if (verificationCode != verifyCode && verifyCode.length > 0){
      wx.showToast({
        title: '验证码有误',
        icon: 'none',
        duration: 1500
      })
    }
  },
  /**
  * 验证通过开始考试
  */
  closeVerify: function(){
    var _this = this;
    _this.setData({
      ["otherInfo.ratifyShow"]: false
    })
    var ordTheme = _this.data.ordTheme;
    if (ordTheme.themeNotice != null && String(ordTheme.themeNotice).length > 0){
      _this.setData({
        ["ordThemeAuxiliary.themeNoticeShow"]: true
      })
    }else{
      var useTime = _this.data.ordThemeSetting.useTime;
      if (useTime != null && parseInt(useTime) > 0) {
        _this.setData({
          ["ordThemeAuxiliary.showTimeCountDown"]: true,
        })
        _this.examTimeCountDown();
      }
    }
  },

  /**
   * 关闭主题公告弹窗
   */
  themeNoticeClose: function(){
    var _this = this;
    _this.setData({
      ["ordThemeAuxiliary.themeNoticeShow"]: false
    })
    var useTime = _this.data.ordThemeSetting.useTime;
    if (useTime != null && parseInt(useTime) > 0) {
      _this.setData({
        ["ordThemeAuxiliary.showTimeCountDown"]: true,
      })
      _this.examTimeCountDown();
    }
  },
  /**
  * 开始倒计时
  */
  examTimeCountDown: function () {
    var _this = this;
    timeCountDown = setInterval(function () {
      var examTime = _this.data.ordThemeAuxiliary.examTime - 1;
      if (examTime >= 0){
        _this.setData({
          ["ordThemeAuxiliary.examTime"]: examTime,
        })
      }
      if (examTime <= 0) {
        _this.setData({
          ["ordThemeAuxiliary.showTimeCountDown"]: false
        })
        clearInterval(timeCountDown);
        timeCountDown = null;
        // 提交
        _this.saveDioachaQuery(false);
      }
    },1000)
  },
  /**
  * 选择测评答案显示类型
  */
  selectExamPanel: function(e){
    var _this = this;
    var sel = e.currentTarget.dataset.id
    _this.setData({
      ["ordThemeAuxiliary.examPanel"]: sel,
    })
  },

  /**
   * 进入用户主页
   */
  navigateToPersonhome: function (e) {
    var openid = e.currentTarget.dataset.openid;
    wx.navigateTo({
      url: '../../../../../ucenter/pages/ucenter/personhome/personhome?openid=' + openid
    })
  },

  /**
   * 进入打卡页面
   */
  doClock: function(){
    var _this = this;
    var themeid = _this.data.themeAnswerSubmit.themeid;
    var circleid = _this.data.ordTheme.circleid;
    wx.redirectTo({
      url: '../../../../../ucenter/pages/ucenter/personcenter/editdetails/circleinteraction/noThemeClock/noThemeClock?themeid=' + themeid + '&circleid=' + circleid,
    })
  },

  /**
   * 测评详情
   */
  navigateToThemeResult: function(){
    var _this = this;
    var themeid = _this.data.themeAnswerSubmit.themeid;
    wx.redirectTo({
      url: 'themeResult/themeResult?themeid=' + _this.data.themeAnswerSubmit.themeid,
    })
  }
})